//引入接口
import { reqGetCode, reqUserRegister,reqUserLogin,reqUserInfo,reqlogout} from '@/api'
import {setToken,getToken,removeToken} from '@/utils/token'
const state = {
    code: '',
    //本地已经存有，get直接查看然后间接的保存
    // token:localStorage.getItem("TOKEN"),
    //引用模块的函数
    token:getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除本地数据
    GETLOGOUT(state) {
        state.token = ''
        state.userInfo = {}
        removeToken()
    },

}
const actions = {
    // 修改购物车勾选产品状态
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //注册
    async UserRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //登录
    async UserLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
            //接收服务器下发的token，它是用户的唯一标识
            commit("USERLOGIN", result.data.token)
            //但是vuex存储数据不持久，需要保存到本地
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            commit("GETUSERINFO", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //退出登录删除信息
    async getlogout({ commit }) {
        let result = await reqlogout()
        if (result.code == 200) {
            commit("GETLOGOUT")
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },

}
const getters = {

}
export default {
    state,
    mutations,
    actions,
    getters
}